package com.glorysoft.lipuxinpda.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.glorysoft.lipuxinpda.R;
import com.glorysoft.lipuxinpda.adapter.InnerItemOnclickListener;
import com.glorysoft.lipuxinpda.adapter.MaterialExchangeAdapter;
import com.glorysoft.lipuxinpda.base.BaseActivity;
import com.glorysoft.lipuxinpda.base.Constant;
import com.glorysoft.lipuxinpda.entity.BaseEntity;
import com.glorysoft.lipuxinpda.entity.KeyValueEntity;
import com.glorysoft.lipuxinpda.entity.MaterialDetailInfoEntity;
import com.glorysoft.lipuxinpda.entity.ShowEqpMaterialListReturnEntity;
import com.glorysoft.lipuxinpda.utils.GsonUtils;
import com.glorysoft.lipuxinpda.utils.NetUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MaterialExchangeActivity extends BaseActivity implements InnerItemOnclickListener {
    private Context mContext;

    private LinearLayout llMain;

    private TextView tv_current_eqp_no;//当前设备

    private RecyclerView rv_data_out;//物料信息

    private ShowEqpMaterialListReturnEntity showEqpMaterialListReturnEntity;//设备物料信息
    private List<MaterialDetailInfoEntity> mMaterialDetailInfoList = new ArrayList<>();//物料信息

    private String sEqpID;//设备号

    private MaterialExchangeAdapter mAdapter;//物料信息适配器

    private int nPosition = 0;//点击物料的位置

    private FreeUI_GeneralFragmentDialog mMessageDialog;//消息提示框

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_material_exchange;
    }

    @Override
    protected void initView() {
        mContext = this;

        llMain = findViewById(R.id.llMain);

        tv_current_eqp_no = findViewById(R.id.tv_current_eqp_no);

        rv_data_out = findViewById(R.id.rv_data_out);


    }

    @Override
    protected void initData() {
        Bundle extras = getIntent().getExtras();
        sEqpID = extras.getString("EQPID");
        tv_current_eqp_no.setText(sEqpID);

        getEqpMaterialInfo();//获取设备物料信息

        //region 测试

//        String sJson = "{\n" +
//                "    \"EQP_ID\":\"2FS106\",\n" +
//                "    \"LIST\":[\n" +
//                "        {\n" +
//                "            \"MATERIAL_TYPE\":\"HubBlade\",\n" +
//                "            \"MTM_TYPE_NAME\":\"硬刀1\",\n" +
//                "            \"LIST\":[\n" +
//                "                {\n" +
//                "                    \"ID_CH\":\"型号\",\n" +
//                "                    \"VALUE\":\"XXXXX\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"ID_CH\":\"刀刃长度\",\n" +
//                "                    \"VALUE\":\"230000\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"ID_CH\":\"刀片厚度\",\n" +
//                "                    \"VALUE\":\"XXX\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"ID_CH\":\"刀片批次号\",\n" +
//                "                    \"VALUE\":\"XXX\"\n" +
//                "                }\n" +
//                "            ]\n" +
//                "        },\n" +
//                "        {\n" +
//                "            \"MATERIAL_TYPE\":\"HubBlade\",\n" +
//                "            \"MTM_TYPE_NAME\":\"硬刀2\",\n" +
//                "            \"LIST\":[\n" +
//                "                {\n" +
//                "                    \"ID_CH\":\"型号\",\n" +
//                "                    \"VALUE\":\"XXXXX\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"ID_CH\":\"刀刃长度\",\n" +
//                "                    \"VALUE\":\"230000\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"ID_CH\":\"刀片厚度\",\n" +
//                "                    \"VALUE\":\"XXX\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"ID_CH\":\"刀片批次号\",\n" +
//                "                    \"VALUE\":\"XXX\"\n" +
//                "                }\n" +
//                "            ]\n" +
//                "        }\n" +
//                "    ]\n" +
//                "}";
//        JSONObject jsonObject = null;

//            jsonObject = new JSONObject(sJson);
//            String data = jsonObject.getString("data");
//        showEqpMaterialListReturnEntity = GsonUtils.getObject(sJson, ShowEqpMaterialListReturnEntity.class);
//        mMaterialDetailInfoList.addAll(showEqpMaterialListReturnEntity.getLIST());
//        List<MaterialDetailInfoEntity> list = object.getLIST();
//        showMaterialList();//显示物料信息

        //endregion

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle(getString(R.string.materialReplacement));
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    //region 接口调用

    //获取设备物料信息
    private void getEqpMaterialInfo() {
        FreeUI_EntityCallBack<BaseEntity<ShowEqpMaterialListReturnEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<ShowEqpMaterialListReturnEntity>>(new TypeToken<BaseEntity<ShowEqpMaterialListReturnEntity>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseEntity<ShowEqpMaterialListReturnEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getSupportFragmentManager())) {
                    showToast(response.body().getMessage(), true);
                    showEqpMaterialListReturnEntity = response.body().getData().getBody();
                    showMaterialList();//显示物料信息
                }
            }

            @Override
            public void onError(Response<BaseEntity<ShowEqpMaterialListReturnEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ShowEqpMaterialList");
            }
        };

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("EQP_ID", sEqpID);//设备号
        map.put("CUR_USERID", Constant.INSTANCE.getLoginEntity().getWORK_NO());//工号
        String method = Constant.INSTANCE.getNET_URL() + "/ShowEqpMaterialList";
        new NetUtils().requestPostNetNews(method, this, map, callBack);
    }

    //下机
    private void  deleteMaterial(String sMaterialName){
        if (TextUtils.isEmpty(sMaterialName)){
            return;
        }

        FreeUI_EntityCallBack<BaseEntity> callBack = new FreeUI_DialogEntityCallBack<BaseEntity>(new TypeToken<BaseEntity>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseEntity> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getSupportFragmentManager())) {
                    showEqpMaterialListReturnEntity.getLIST().remove(nPosition);
                    mMaterialDetailInfoList.remove(nPosition);
                    mAdapter.setmList(mMaterialDetailInfoList);
                    showToast(response.body().getMessage(), true);
                }
            }

            @Override
            public void onError(Response<BaseEntity> response) {
                super.onError(response);
                loadError(response.getException(), "DeleteMaterial");
            }
        };

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("EQP_ID", sEqpID);//设备号
        map.put("CUR_USERID", Constant.INSTANCE.getLoginEntity().getWORK_NO());//工号
        map.put("MTM_TYPENAME", sMaterialName);//工号
        String method = Constant.INSTANCE.getNET_URL() + "/DeleteMaterial";
        new NetUtils().requestPostNetNews(method, this, map, callBack);
    }

    //endregion

    //显示物料信息
    private void showMaterialList() {

        if (mMaterialDetailInfoList.size() > 0) {
            mAdapter = new MaterialExchangeAdapter();
            mAdapter.setmList(mMaterialDetailInfoList);
            mAdapter.setOnInnerItemOnClickListener(this);


            //竖直排列、正向排序
            rv_data_out.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
            rv_data_out.setAdapter(mAdapter);
        }
    }

    //消息提示框
    private void showMessageDialog(String message) {
        mMessageDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_prompt2, null);
        Button btnConfirm = view.findViewById(R.id.btnConfirm);
        Button btnCancel = view.findViewById(R.id.btnCancel);
        TextView tvTips = view.findViewById(R.id.tvTips);
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMessageDialog.dismiss();
                String mtm_type_name = mMaterialDetailInfoList.get(nPosition).getMTM_TYPE_NAME();
                deleteMaterial(mtm_type_name);//物料下机
                //region 测试
//                showEqpMaterialListReturnEntity.getLIST().remove(nPosition);
//                mMaterialDetailInfoList.remove(nPosition);
//                mAdapter.setmList(mMaterialDetailInfoList);
                //endregion
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMessageDialog.dismiss();
            }
        });
        tvTips.setText(message);
        mMessageDialog.setLayout(view);
//        mDieTypeDialog.getDialog().setCanceledOnTouchOutside(false);
        mMessageDialog.show(getSupportFragmentManager(), "isDelete");
        mMessageDialog.setCallBack(new FreeUI_CommonCallback() {
            @Override
            public void onSuccess() {
                mMessageDialog = null;
            }
        });

    }

    @Override
    public void itemClick(View v, int position) {
        if (v.getId() == R.id.btn_down) {
            nPosition = position;
            String mtm_type_name = mMaterialDetailInfoList.get(position).getMTM_TYPE_NAME();
            showMessageDialog(String.format(getResources().getString(R.string.is_confirm_disembark), mtm_type_name));

        } else if (v.getId() == R.id.btn_exchange) {
            nPosition = position;
            Intent intent = new Intent(getBaseContext(), MaterialExchangeScanActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("EQPID", sEqpID);
            intent.putExtra("showPlugin", "header");
            intent.putExtra("MATERIALTYPE", mMaterialDetailInfoList.get(position).getMATERIAL_TYPE());
            startActivityForResult(intent, 105);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == -2 && requestCode == 105){
            Bundle extras = data.getExtras();
            List<KeyValueEntity> list = new ArrayList<>();
            list = (List<KeyValueEntity>) extras.getSerializable("list");
            if (list.size() > 0){
                mMaterialDetailInfoList.get(nPosition).setLIST(list);
                mAdapter.setmList(mMaterialDetailInfoList);
            }
        }
    }
}